//
//  KVNHomeViewController.m
//  Test1
//
//  Created by KelvinYeung on 15/7/15.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNHomeViewController.h"
#import "KVNSlideView.h"
#import "KVNSlideViewItem.h"
#import "KVNInfoItem.h"
#import "KVNHomeNewsItem.h"
#import "KVNHomeHotSource.h"
#import "KVNHouseSummary.h"
#import "MKNetworkKit.h"
#import "AppDelegate.h"
#import "KVNScrollView.h"
#import "KVNAreaViewController.h"
#import "KVNGroupbuyViewController.h"
#import "KVNFakeViewController.h"
#import "KVNGroupbuyDetailViewController.h"
#import "KVNWebViewController.h"

@interface KVNHomeViewController ()


@property UIButton *regionBtn;
@property int timeCount;
@property UIScrollView * imageScrollView;
@property UIPageControl * bannerPageControl;
@property KVNHomeHotSource *hotSrcView;
@property UIScrollView *mainView ;
@property KVNSlideView *bannerView;//轮播图
@property KVNInfoItem *infoItem1;
@property KVNInfoItem *infoItem2;
@property KVNInfoItem *infoItem3;
@property KVNInfoItem *infoItem4;
@property KVNHomeNewsItem *newsItem1;
@property KVNHomeNewsItem *newsItem2;
@property KVNHomeNewsItem *newsItem3;
@property KVNHomeNewsItem *newsItem4;
@property NSArray * newsItemsData;
@property BOOL isLoading;
@property UIView *refresher;
@end

@implementation KVNHomeViewController
@synthesize timeCount;
@synthesize imageScrollView;
@synthesize bannerPageControl;
@synthesize hotSrcView;
@synthesize mainView;
@synthesize bannerView;
@synthesize infoItem1;
@synthesize infoItem2;
@synthesize infoItem3;
@synthesize infoItem4;
@synthesize newsItem1;
@synthesize newsItem2;
@synthesize newsItem3;
@synthesize newsItem4;
@synthesize regionBtn;

- (void)viewDidLoad {
    [super viewDidLoad];
   
    CGRect appFrame =[[UIScreen mainScreen] applicationFrame];
    
    //定义一个scrollView
    mainView = [[UIScrollView alloc] init];
    mainView.delegate = self;
    mainView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    mainView.autoresizesSubviews = YES;
    mainView.showsVerticalScrollIndicator = NO;
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
    mainView.alwaysBounceVertical = YES;
    self.view = mainView;

    
    //搜索框
    UISearchBar *tv1 = [[UISearchBar alloc] init];
    tv1.frame = CGRectMake(0, 0, 200, 30);
    tv1.placeholder = @"楼盘名/开发商";
    [tv1 setSearchBarStyle:UISearchBarStyleDefault];
 
    //去除searchbar背景
    for (UIView *view in tv1.subviews) {
        // for before iOS7.0
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
            break;
        }
        // for later iOS7.0(include)
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    

    //左边logo
    UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_logo"]];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] init];
    leftBarButtonItem.customView = logoView ;
    
    //右边按钮
    UIImage *arrow_down =[UIImage imageNamed:@"arrow_down"];
    regionBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [regionBtn setTitle:@"广州市" forState: UIControlStateNormal];
    //regionBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [regionBtn setImage:arrow_down forState:UIControlStateNormal];
    [regionBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [regionBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -arrow_down.size.width-5, 0,arrow_down.size.width-10)];
    [regionBtn setImageEdgeInsets:UIEdgeInsetsMake(0,70-arrow_down.size.width,0,-70+arrow_down.size.width)];
    [regionBtn addTarget:self action:@selector(regionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] init];
    rightBarButtonItem.customView = regionBtn;
    
    
    
    //导航栏
    self.navigationItem.titleView =tv1;
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //设置scrollView不留白
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //Banner轮播图-----------------------------------------------------------------
    bannerView = [[KVNSlideView alloc]initWithFrame:CGRectMake(0, 32, appFrame.size.width, 170)];
   // KVNSlideViewItem *slideItem1 = [[KVNSlideViewItem alloc]init];
    //slideItem1.image = [UIImage imageNamed:@"banner1.jpg"];
    //KVNSlideViewItem *slideItem2 = [[KVNSlideViewItem alloc]init];
    //slideItem2.image = [UIImage imageNamed:@"banner2.jpg"];
    //NSArray *bannerArray = @[slideItem1,slideItem2];
    //[bannerView setViews:bannerArray];
    __weak UIViewController *weakSelf = self;
    bannerView.slideViewItemClick = ^(NSDictionary * dic){
        NSLog(@"KVNHomeViewController ScrollView is Click..%@",[dic valueForKey:@"objectType"]);
        
        //团购
        if (![[dic valueForKey:@"objectType"] isEqual:[NSNull null]] && [[dic valueForKey:@"objectType"] intValue]== 1) {
            
            if (![[dic valueForKey:@"objectId"] isEqual:[NSNull null]]) {
                KVNGroupbuyDetailViewController *controller = [[KVNGroupbuyDetailViewController alloc] init];
                controller.houseId = [[dic valueForKey:@"objectId"] integerValue];
                [weakSelf.tabBarController.tabBar setHidden:YES];
                [weakSelf.navigationController pushViewController:controller animated:YES];
            }
            
            
        }else if (![[dic valueForKey:@"objectType"] isEqual:[NSNull null]] && [[dic valueForKey:@"objectType"] intValue]== 2) {
            //团租
            if (![[dic valueForKey:@"objectId"] isEqual:[NSNull null]]) {
                KVNGroupbuyDetailViewController *controller = [[KVNGroupbuyDetailViewController alloc] init];
                controller.houseId = [[dic valueForKey:@"objectId"] integerValue];
                [weakSelf.tabBarController.tabBar setHidden:YES];
                [weakSelf.navigationController pushViewController:controller animated:YES];
            }
            
            
        }else if (![[dic valueForKey:@"objectType"] isEqual:[NSNull null]] && [[dic valueForKey:@"objectType"] intValue]== 3) {
            //房源
            if (![[dic valueForKey:@"objectId"] isEqual:[NSNull null]]) {
                KVNGroupbuyDetailViewController *controller = [[KVNGroupbuyDetailViewController alloc] init];
                controller.houseId = [[dic valueForKey:@"objectId"] integerValue];
                [weakSelf.tabBarController.tabBar setHidden:YES];
                [weakSelf.navigationController pushViewController:controller animated:YES];
            }
            
            
        }
        
        
    };
    [self.view addSubview:bannerView];
    
    
    
    //四个按钮---------------------------------------------------
    infoItem1 = [[KVNInfoItem alloc] init];
    infoItem1.frame = CGRectMake(0, 233, appFrame.size.width*0.5, 70);
    infoItem1.backgroundColor = [UIColor whiteColor];
    [infoItem1 setTitle:@"团购"];
    [infoItem1 setContent:@"团购新房优惠多多"];
    [infoItem1 setImage:[UIImage imageNamed:@"sale.png"]];
    
    
    infoItem2 = [[KVNInfoItem alloc] init];
    infoItem2.frame = CGRectMake(appFrame.size.width*0.5, 233, appFrame.size.width*0.5, 70);
    infoItem2.backgroundColor = [UIColor whiteColor];
    [infoItem2 setTitle:@"团租"];
    [infoItem2 setContent:@"团租新房优惠多多"];
    [infoItem2 setImage:[UIImage imageNamed:@"rent.png"]];
    
    infoItem3 = [[KVNInfoItem alloc] init];
    infoItem3.frame = CGRectMake(0, 303, appFrame.size.width*0.5, 70);
    infoItem3.backgroundColor = [UIColor whiteColor];
    [infoItem3 setTitle:@"房源"];
    [infoItem3 setContent:@"团租新房优惠多多"];
    [infoItem3 setImage:[UIImage imageNamed:@"source.png"]];
    
    infoItem4 = [[KVNInfoItem alloc] init];
    infoItem4.frame = CGRectMake(appFrame.size.width*0.5, 303, appFrame.size.width*0.5, 70);
    infoItem4.backgroundColor = [UIColor whiteColor];
    [infoItem4 setTitle:@"特价商铺"];
    [infoItem4 setContent:@"团租新房优惠多多"];
    [infoItem4 setImage:[UIImage imageNamed:@"discount.png"]];
    
    [self.view addSubview:infoItem1];
    [self.view addSubview:infoItem2];
    [self.view addSubview:infoItem3];
    [self.view addSubview:infoItem4];
    
    
    UITapGestureRecognizer *infoItemTapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoItemClick:)];
    infoItemTapGestureRecognizer1.numberOfTapsRequired = 1;
    infoItemTapGestureRecognizer1.numberOfTouchesRequired = 1;
    UITapGestureRecognizer *infoItemTapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoItemClick:)];
    infoItemTapGestureRecognizer2.numberOfTapsRequired = 1;
    infoItemTapGestureRecognizer2.numberOfTouchesRequired = 1;
    UITapGestureRecognizer *infoItemTapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoItemClick:)];
    infoItemTapGestureRecognizer3.numberOfTapsRequired = 1;
    infoItemTapGestureRecognizer3.numberOfTouchesRequired = 1;
    UITapGestureRecognizer *infoItemTapGestureRecognizer4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoItemClick:)];
    infoItemTapGestureRecognizer4.numberOfTapsRequired = 1;
    infoItemTapGestureRecognizer4.numberOfTouchesRequired = 1;
    [infoItem1 addGestureRecognizer:infoItemTapGestureRecognizer1];
    [infoItem2 addGestureRecognizer:infoItemTapGestureRecognizer2];
    [infoItem3 addGestureRecognizer:infoItemTapGestureRecognizer3];
    [infoItem4 addGestureRecognizer:infoItemTapGestureRecognizer4];
    infoItem1.tag = 1;
    infoItem2.tag = 2;
    infoItem3.tag = 3;
    infoItem4.tag = 4;
    
    
    
    //更多服务
    UIView *moreSvcView = [[UIView alloc] initWithFrame:CGRectMake(0, 383, appFrame.size.width, 80)];
    moreSvcView.backgroundColor = [UIColor whiteColor];
    UILabel *moreSvcLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 11, appFrame.size.width*0.5, 20)];
    moreSvcLabel.text = @"更多服务";
    moreSvcLabel.font = [UIFont systemFontOfSize:12];
    moreSvcLabel.textColor = [UIColor lightGrayColor];
    [moreSvcView addSubview:moreSvcLabel];
    
    //计算器
    UIButton *calcBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 36, 100, 40)];
    calcBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //findPriceBtn.backgroundColor = [UIColor purpleColor];
    [calcBtn setImage:[UIImage imageNamed:@"home_btn_the_computer"]  forState:UIControlStateNormal];
    [calcBtn setTitle:@"计算机" forState:UIControlStateNormal];
    [calcBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [calcBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    calcBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [calcBtn setImageEdgeInsets:UIEdgeInsetsMake(2, 2, 5, 64)];
    [calcBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -26, 0, 0)];
    [moreSvcView addSubview:calcBtn];
    calcBtn.tag = 1;
    [calcBtn addTarget:self action:@selector(handleFakeController:) forControlEvents:UIControlEventTouchUpInside];

    
    
    //查房价
    UIButton *findPriceBtn = [[UIButton alloc]initWithFrame:CGRectMake(130, 36, 100, 40)];
    findPriceBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //findPriceBtn.backgroundColor = [UIColor purpleColor];
    [findPriceBtn setImage:[UIImage imageNamed:@"home_btn_check_prices"]  forState:UIControlStateNormal];
    [findPriceBtn setTitle:@"查房价" forState:UIControlStateNormal];
    [findPriceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [findPriceBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    findPriceBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [findPriceBtn setImageEdgeInsets:UIEdgeInsetsMake(2, 2, 5, 64)];
    [findPriceBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -26, 0, 0)];
    [moreSvcView addSubview:findPriceBtn];
    findPriceBtn.tag =2;
    [findPriceBtn addTarget:self action:@selector(handleFakeController:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *findInMapBtn = [[UIButton alloc]initWithFrame:CGRectMake(240, 36, 100, 40)];
    findInMapBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //findPriceBtn.backgroundColor = [UIColor purpleColor];
    [findInMapBtn setImage:[UIImage imageNamed:@"home_btn_the_map"]  forState:UIControlStateNormal];
    [findInMapBtn setTitle:@"地图" forState:UIControlStateNormal];
    [findInMapBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [findInMapBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    findInMapBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [findInMapBtn setImageEdgeInsets:UIEdgeInsetsMake(2, 2, 5, 64)];
    [findInMapBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -26, 0, 0)];
    [moreSvcView addSubview:findInMapBtn];
    findInMapBtn.tag = 3;
    [findInMapBtn addTarget:self action:@selector(handleFakeController:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:moreSvcView];
    
    
    //动态信息
    newsItem1 = [[KVNHomeNewsItem alloc] init];
    newsItem1.frame = CGRectMake(0, 473, appFrame.size.width*0.5, 70);
    newsItem1.backgroundColor = [UIColor whiteColor];
    //[newsItem1 setTitle:@"O元疯狂抢"];
    //[newsItem1 setContent:@"5000置业基金"];
    //[newsItem1 setImage:[UIImage imageNamed:@"sale.png"]];
    newsItem1.titleLabel.textColor = [UIColor orangeColor];
    
    newsItem2 = [[KVNHomeNewsItem alloc] init];
    newsItem2.frame = CGRectMake(appFrame.size.width*0.5, 473, appFrame.size.width*0.5, 70);
    newsItem2.backgroundColor = [UIColor whiteColor];
    //[newsItem2 setTitle:@"免费送苹果"];
    //[newsItem2 setContent:@"疯了，润佳商场"];
    //[newsItem2 setImage:[UIImage imageNamed:@"rent.png"]];
    newsItem2.titleLabel.textColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.8];
    newsItem3 = [[KVNHomeNewsItem alloc] init];
    newsItem3.frame = CGRectMake(0, 543, appFrame.size.width*0.5, 70);
    newsItem3.backgroundColor = [UIColor whiteColor];
    //[newsItem3 setTitle:@"最靓房源"];
    //[newsItem3 setContent:@"欧洲城随你选"];
    //[newsItem3 setImage:[UIImage imageNamed:@"source.png"]];
    newsItem3.titleLabel.textColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.5];
    
    newsItem4 = [[KVNHomeNewsItem alloc] init];
    newsItem4.frame = CGRectMake(appFrame.size.width*0.5, 543, appFrame.size.width*0.5, 70);
    newsItem4.backgroundColor = [UIColor whiteColor];
    //[newsItem4 setTitle:@"最高减一半"];
    //[newsItem4 setContent:@"万达商城期待你"];
    //[newsItem4 setImage:[UIImage imageNamed:@"discount.png"]];
    newsItem4.titleLabel.textColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.5];
    
    [self.view addSubview:newsItem1];
    [self.view addSubview:newsItem2];
    [self.view addSubview:newsItem3];
    [self.view addSubview:newsItem4];
    
    //点击事件
    UITapGestureRecognizer * newsItemTapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleNewsItemTap:)];
    UITapGestureRecognizer * newsItemTapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleNewsItemTap:)];
    UITapGestureRecognizer * newsItemTapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleNewsItemTap:)];
    UITapGestureRecognizer * newsItemTapGestureRecognizer4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleNewsItemTap:)];
    newsItem1.tag = 0;
    newsItem2.tag = 1;
    newsItem3.tag = 2;
    newsItem4.tag = 3;
    [newsItem1 addGestureRecognizer:newsItemTapGestureRecognizer1];
    [newsItem2 addGestureRecognizer:newsItemTapGestureRecognizer2];
    [newsItem3 addGestureRecognizer:newsItemTapGestureRecognizer3];
    [newsItem4 addGestureRecognizer:newsItemTapGestureRecognizer4];
    
    
    
    
    //热门团租、热门团购
    hotSrcView = [[KVNHomeHotSource alloc] init];
    hotSrcView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    hotSrcView.frame = CGRectMake(0, 623, appFrame.size.width, 64);
    [self.view addSubview:hotSrcView];
    [hotSrcView reloadData];
    
    mainView.contentSize = CGSizeMake(0, 800);
    
    
    [self refreshData];
    
    
    
    //注册观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(regionWillChange:) name:@"KVN_REGION_WILL_CHANGE" object:nil];
    //hotSrcView加载完数据后通知变更frame大小
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeViewWillLayout:) name:@"KVN_HOME_VIEW_WILL_LAYOUT" object:nil];
    //hotSrc的cell点击后通知显示详细资料
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeViewWillShowHouseDetails:) name:@"KVN_HOME_VIEW_WILL_SHOW_HOT_SRC_DETAIL" object:nil];
    
}


#pragma mark - handlerFakeCOntroller
-(void)handleFakeController:(UIButton *)sender{
    KVNFakeViewController *controller = [[KVNFakeViewController alloc] init];
    
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    self.navigationItem.backBarButtonItem = item;

    switch (sender.tag) {
        case 1:
            controller.controllerType = KVN_FAKE_VIEW_CALCULATOR;
            item.title = @"房贷计算";
            break;
          
        case 2:
            controller.controllerType = KVN_FAKE_VIEW_CHECK_PRICE;
            item.title = @"快速查房价";
            break;
            
        case 3:
            controller.controllerType = KVN_FAKE_VIEW_MAP;
            item.title = @"团购";
            break;
        default:
            break;
    }
   [self.tabBarController.tabBar setHidden:YES];
    [self.navigationController pushViewController:controller animated:YES];
    
}

#pragma mark --处理InfoItem 的点击事件
- (void) infoItemClick:(UITapGestureRecognizer*) sender{
    NSLog(@"tap.........");
    [ApplicationDelegate.httpRequestEngine cancelAllOperations];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    self.navigationItem.backBarButtonItem = backItem;
    KVNGroupbuyViewController *groupbuyViewController = [[KVNGroupbuyViewController alloc]init];
    
    switch (sender.view.tag) {
        case 1:
            [backItem setTitle:@"团购"];
            groupbuyViewController.activityCategoryId = @1;
            break;
        case 2:
            [backItem setTitle:@"团租"];
            groupbuyViewController.activityCategoryId = @2;
            break;
        case 3:
            [backItem setTitle:@"房源"];
            groupbuyViewController.activityCategoryId = @3;
            break;
        case 4:
            [backItem setTitle:@"特价商铺"];
            groupbuyViewController.activityCategoryId = @3;
            break;
        default:
            break;
    }
    [self.tabBarController.tabBar setHidden:YES];
    [self.navigationController pushViewController:groupbuyViewController animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (void) refreshData{
    
    //banner
    NSArray *homeBannersFromStore  = [ApplicationDelegate.dataStoreEngine queryWithEntityName:@"HomeBanners" sortDescriptor:nil];
    
    if(homeBannersFromStore.count==0){
        
        [ApplicationDelegate.httpRequestEngine postWithPath:@"/banner/homeBanners.do" json:nil completionHandler:^(MKNetworkOperation *completedOperation) {
            
            
            NSArray *data = [[completedOperation responseJSON] objectForKey:@"data"];
            [bannerView setData:data];
            //保存数据
            for (int i =0 ; i<data.count; i++) {
                [ApplicationDelegate.dataStoreEngine updateDataForName:@"HomeBanners" object:data[i]];
            }

            
            
        } errorHandler:^(NSError *error) {
            //...
        }];
    
    }else{
    
        
        [bannerView setData:homeBannersFromStore];

        [ApplicationDelegate.httpRequestEngine postWithPath:@"/banner/homeBanners.do" json:nil completionHandler:^(MKNetworkOperation *completedOperation) {
            
            NSArray *data = [[completedOperation responseJSON] objectForKey:@"data"];
            [bannerView setData:data];
            //保存数据
            for (int i =0 ; i<data.count; i++) {
                [ApplicationDelegate.dataStoreEngine updateDataForName:@"HomeBanners" object:data[i]];
            }
            
            
            
        } errorHandler:^(NSError *error) {
            //...
        }];
        
        
        
    }
    
    
    
    //首页广告/house/adList.do
    NSArray *homeNewsFromStore  = [ApplicationDelegate.dataStoreEngine queryWithEntityName:@"HomeNews" sortDescriptor:nil];
    
    if(homeNewsFromStore.count==0){
        NSLog(@"queryWithEntityName is Empty");
        [ApplicationDelegate.httpRequestEngine postWithPath:@"/house/adList.do" json:nil completionHandler:^(MKNetworkOperation *completedOperation) {
            
            NSArray *data = [[completedOperation responseJSON] objectForKey:@"data"];
            [self setHomeNewsItemsData:data];
            for (int i =0 ; i<data.count; i++) {
                [ApplicationDelegate.dataStoreEngine updateDataForName:@"HomeNews" object:data[i]];
            }

        } errorHandler:^(NSError *error) {
            //...
        }];
        

    }else{
        NSLog(@"queryWithEntityName is not Empty");
        [self setHomeNewsItemsData:homeNewsFromStore];
        NSLog(@"queryWithEntityName is Empty");
        [ApplicationDelegate.httpRequestEngine postWithPath:@"/house/adList.do" json:nil completionHandler:^(MKNetworkOperation *completedOperation) {
            NSArray *data = [[completedOperation responseJSON] objectForKey:@"data"];
            [self setHomeNewsItemsData:data];
            for (int i =0 ; i<data.count; i++) {
                [ApplicationDelegate.dataStoreEngine updateDataForName:@"HomeNews" object:data[i]];
            }
            
        } errorHandler:^(NSError *error) {
            //...
        }];
    }
    
    
    
}


- (void) setHomeNewsItemsData:(NSArray*) data{
    _newsItemsData = data;
    if([data[0] isKindOfClass:[NSManagedObject class]]){
        [newsItem1 setData:[data[0] dictionaryWithValuesForKeys:nil] ];
        [newsItem2 setData:[data[1] dictionaryWithValuesForKeys:nil]];
        [newsItem3 setData:[data[2] dictionaryWithValuesForKeys:nil]];
        [newsItem4 setData:[data[3] dictionaryWithValuesForKeys:nil]];
    }else{
        [newsItem1 setData:data[0]];
        [newsItem2 setData:data[1]];
        [newsItem3 setData:data[2]];
        [newsItem4 setData:data[3]];
    
    }
    [newsItem1 setNeedsDisplay];
    [newsItem2 setNeedsDisplay];
    [newsItem3 setNeedsDisplay];
    [newsItem4 setNeedsDisplay];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{
    
    // 假设偏移表格高度的20%进行刷新
    
    if(_refresher !=nil){
        NSLog(@"调用上拉刷新方法 Y:%f",((UIScrollView *)self.view).contentOffset.y);
        _refresher.frame=CGRectMake(0, ((UIScrollView *)self.view).contentOffset.y, _refresher.frame.size.width, _refresher.frame.size.height);
        [_refresher setNeedsLayout];
    }
    
    if (!_isLoading) { // 判断是否处于刷新状态，刷新中就不执行
        
        

        // 取内容的高度：
        
        //    如果内容高度大于UIScrollView高度，就取TableView高度
        
        //    如果内容高度小于UITableView高度，就取内容的实际高度
        
        float height = ((UIScrollView *)self.view).contentSize.height > self.view.frame.size.height ?self.view.frame.size.height : ((UIScrollView *)self.view).contentSize.height;
        
        
        if ((height - scrollView.contentSize.height + scrollView.contentOffset.y) / height > 0.2) {
            
            // 调用上拉刷新方法
            NSLog(@"调用上拉刷新方法");
            
            
            
            
        }
        
        
        if (- ((UIScrollView*)self.view).contentOffset.y / self.view.frame.size.height > 0.2) {
            _isLoading = YES;
            // 调用下拉刷新方法
            NSLog(@"调用下拉刷新方法");
            if(self.refresher == nil){
                NSLog(@"调用下拉刷新方法123123123123");

                CGPoint contentOffset = ((UIScrollView*)self.view).contentOffset;
                _refresher = [[UIView alloc] init];
                _refresher.frame = CGRectMake(0, contentOffset.y, 320, 60);
                _refresher.backgroundColor = [UIColor redColor];
                [self.view addSubview:_refresher];
                UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                [_refresher setContentMode:UIViewContentModeCenter];
                [_refresher addSubview:indicator];
            }
            
            [(UIActivityIndicatorView *)[_refresher.subviews objectAtIndex:0] startAnimating];
            [(UIActivityIndicatorView *)[_refresher.subviews objectAtIndex:0]  setHidden:NO];

        }
        
    }
    
}

- (void)regionBtnClick:(UIControlEvents*) sender{
    //停止所有网络请求
    [ApplicationDelegate.httpRequestEngine cancelAllOperations];
    
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] init];
    [buttonItem setTitle:@"选择城市"];
    self.navigationItem.backBarButtonItem = buttonItem;
    KVNAreaViewController *areaViewController = [[KVNAreaViewController alloc]init];
    [self.tabBarController.tabBar setHidden:YES];
    [self.navigationController pushViewController:areaViewController animated:YES];
    

}
#pragma mark -- 观察者响应
- (void)regionWillChange:(NSNotification*) notification{
    id regionName = [notification object];
    [regionBtn setTitle:(NSString *)regionName forState:UIControlStateNormal];
    
}

- (void)homeViewWillLayout:(NSNotification*) notification{
    [self.view layoutIfNeeded];
    mainView.contentSize = CGSizeMake(0, hotSrcView.frame.origin.y + hotSrcView.frame.size.height);
    
}

- (void)homeViewWillShowHouseDetails:(NSNotification*) notification{
    NSLog(@"houseIDAA::::%ld",[[notification object] integerValue]);
    NSInteger houseId = [[notification object] integerValue];
    KVNGroupbuyDetailViewController *controller = [[KVNGroupbuyDetailViewController alloc] init];
    controller.houseId = houseId;
    [self.tabBarController.tabBar setHidden:YES];
    [self.navigationController pushViewController:controller animated:YES];
}


- (void)handleNewsItemTap:(UITapGestureRecognizer*)sender{

    UIView *view = [sender view];
    KVNWebViewController *controller = [[KVNWebViewController alloc] init];
    controller.requestUrl = [[_newsItemsData objectAtIndex:view.tag] valueForKey:@"url"];
    
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] init];
    [backButtonItem setTitle:@"返回"];
    UINavigationController *targetController = [self.tabBarController.viewControllers objectAtIndex:1];
    UIViewController *topViewController = [targetController topViewController];
    [topViewController.navigationItem setBackBarButtonItem:backButtonItem];
    [targetController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.tabBarController setSelectedIndex:1];
    [targetController pushViewController:controller animated:YES];
    
}


- (void) viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   // [self.tabBarController.tabBar setHidden:YES];
    

    
    
    

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:NO];

}


@end
